<template>
  <nav ref="nav" class="build-navBox">
    <ul :class="['build-nav','nav','clearfix',navBarFixed == true ? 'navBarWrap' :'']">
      <li :style="`width: ${1180/navData.navList.length}px;`" :class="{'active': curindex === index}" v-for="(item, index) in navData.navList" :key="index">
        <a :href="'#'+item.id">{{item.name}}</a>
      </li>
    </ul>
  </nav>
</template>

<script>
  export default {
    name: "navigation",
    props: {
      navData: {},
    },
    data() {
      return {
        navBarFixed: false,
        curindex: 0
      }
    },
    mounted() {
      window.addEventListener('scroll', this.initScroll)
    },
    methods: {
      initScroll() {
        let _this = this;
        // 监听页面滚动事件
        var delClass = function (obj, cls) {
          if (obj.className == cls) {
            obj.className = "";
          }
        };
        var incClass = function (obj, cls) {
          if (obj.className != cls) {
            obj.className = cls;
          }
        };

        var pos = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
        if (pos > _this.navData.top) {
          _this.navBarFixed = true;
        } else {
          _this.navBarFixed = false;
        }

        var navList = document.querySelector("#nav").querySelectorAll("li");
        var items = document.querySelector("#main").querySelectorAll(".anchor");

        // 滚动后遍历元素，如果页面滚动位置大于元素的位置，赋值给变量
        var currentId = "";
        for (var i = 0; i < items.length; i++) {
          var _item = items[i];
          var _itemTop = 0;
          var par = _item.offsetParent;
          if (par.nodeName.toLowerCase() == "body") {
            _itemTop = _item.offsetTop;
          } else {
            while (par) {
              _itemTop += par.offsetTop;
              par = par.offsetParent;
            }
          }
          if (pos > _itemTop - 123) {
            currentId = _item.id;
          } else {
            break;
          }
        }
        // 如果已赋值了变量，进行匹配，如果匹配则添加class其他删除
        if (currentId) {
          for (var j = 0; j < navList.length; j++) {
            var _navItem = navList[j];
            var _navId = _navItem.children[0].hash.replace(/#/g, '');
            if (_navId != currentId) {
              delClass(_navItem, "active");
            } else {
              incClass(_navItem, "active");
            }
          }
        }
      }
    },
    destroyed () {
      window.removeEventListener('scroll', this.initScroll)
    }
  }
</script>

<style scoped>
  .navBarWrap {
    position: fixed;
    top: 0;
  }
</style>
